package com.pjhouse.pipeline;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import com.alibaba.citrus.service.pipeline.PipelineContext;
import com.alibaba.citrus.service.pipeline.support.AbstractValve;
import com.alibaba.citrus.service.uribroker.URIBrokerService;
import com.alibaba.citrus.turbine.TurbineRunData;
import com.alibaba.citrus.turbine.util.TurbineUtil;
import com.pjhouse.core.user.domain.Role;
import com.pjhouse.core.user.service.UserService;
import com.pjhouse.pipeline.context.LoginContextHolder;
import com.pjhouse.pipeline.security.UrlProtectMappingService;
public class LoginValve extends AbstractValve {
	@Resource
	private HttpServletRequest request;
	@Resource
	protected URIBrokerService uriBrokerService;
	@Resource
	private UrlProtectMappingService urlProtectMappingService;
	@Resource
	private UserService userService;
	
	@Override
	public void invoke(PipelineContext pipelineContext) throws Exception {

		try {
			TurbineRunData rundata = TurbineUtil.getTurbineRunData(request);

			// 将cookie 中的用户信息到 ThreadLocal
			LoginContextHolder.setupLoginContext(request);

			// 检查URL 是否必登录状态
			if (checkNeedLogin()) {
				rundata.setRedirectLocation(uriBrokerService.getURIBroker("loginLink").render());
				return;
			}
			// 验证用户是否有权限访问
			if(checkCanVisit()){
				rundata.setRedirectLocation(uriBrokerService.getURIBroker("errorLink").render());
				return;
			}
			pipelineContext.invokeNext();
		}finally{
			LoginContextHolder.clearLoginContext();
		}
	}
	
	/**
	 * 检查URL 是否是在必须登录的配置中
	 * 
	 * @return 
	 */
	private boolean checkNeedLogin() {
		TurbineRunData rundata = TurbineUtil.getTurbineRunData(request);
		String target = rundata.getTarget();

		if (LoginContextHolder.getLoginContext().getId() > 0) {// 已经登录
			return false;
		}
		if (urlProtectMappingService.isURLUnProtected(target)) {
			return false;
		} else {
			return true;
		}
	}
	
	/**
	 * 验证用户是否可以访问
	 * @return
	 */
	private boolean checkCanVisit(){
		TurbineRunData rundata = TurbineUtil.getTurbineRunData(request);
		String target = rundata.getTarget();

		if (LoginContextHolder.getLoginContext().getId() > 0) {// 已经登录
			return true;
		}
		String roleName = LoginContextHolder.getLoginContext().getRole();
		Role role = Role.get(roleName);
		for (String str : role.getUris()) {
			if(target.startsWith(str))
				return true;
		}
		return false;
	}

}
